/*
给定一个正整数 n，生成一个包含 1 到 n² 所有元素，且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

 */
public class LeetCode_59 {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int i = 1;
        int X_Begin = 0;
        int X_End = n - 1;
        int Y_Begin = 0;
        int Y_End = n - 1;
        while (i <= n * n){
            //水平向右
            for (int j = X_Begin; j <= X_End; j++){
                res[Y_Begin][j] = i++;
            }
            Y_Begin++;

            //垂直向下
            for (int j = Y_Begin; j <= Y_End; j++){
                res[j][X_End] = i++;
            }
            X_End--;

            //水平向左
            for (int j = X_End; j >= X_Begin; j--){
                res[Y_End][j] = i++;
            }
            Y_End--;

            //水平向上
            for (int j = Y_End; j >= Y_Begin; j--){
                res[j][X_Begin] = i++;
            }
            X_Begin++;
        }

        return res;
    }
}
